﻿using Common;
using CommonModel;
using CommonModel.Config;
using IBll;
using RabbitMQ.Client;
using System.Text;

namespace Bll
{
    /// <summary>
    /// Mq服务
    /// </summary>
    public class MqBll : IMqBll
    {
        private static IConnection Connection { get; set; }

        /// <summary>
        /// 生产消息
        /// </summary>
        /// <param name="mqMessage"></param>
        /// <returns></returns>
        public bool ProduceMessage(MqMessage mqMessage)
        {
            bool result = false;

            if (Connection == null || !Connection.IsOpen)
            {
                Connection = GetConnection();
            }
            if (Connection != null && Connection.IsOpen)
            {
                using (var channel = Connection.CreateModel())
                {
                    channel.QueueDeclare(mqMessage.MessageQueue, true, false, false, null);//持久化
                    channel.ExchangeDeclare("", "");
                    var properties = channel.CreateBasicProperties();
                    properties.DeliveryMode = 2;//持久化
                    channel.BasicPublish("", mqMessage.MessageQueue, properties, Encoding.UTF8.GetBytes(mqMessage.ToJson()));
                    result = true;
                }
            }
            else
            {
                LogHelper.Debug("获取Mq链接为空或者非打开状态");
            }

            return result;
        }

        #region 私有方法
        /// <summary>
        /// 获取一个Mq链接
        /// </summary>
        /// <returns></returns>
        private IConnection GetConnection()
        {
            IConnection connection = null;

            var connectionFactory = new ConnectionFactory();
            connectionFactory.HostName = MqConfig.HostName;
            connectionFactory.UserName = MqConfig.UserName;
            connectionFactory.Password = MqConfig.Password;
            //connectionFactory.Port = "";
            connection = connectionFactory.CreateConnection();
            connection.AutoClose = false;

            return connection;
        }
        #endregion

    }
}
